using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace VoxelEngine.Utils
{
	public class DynamicObjectPool : MonoBehaviour
	{
		[SerializeField]
		private PoolDescription[] pools;

		private List<PoolDescription> _poolList;

		public int frame;

		public static DynamicObjectPool Instance
		{
			get;
			private set;
		}

		private void Awake()
		{
			Instance = this;
		}

		private IEnumerator Start()
		{
			yield return null;
			_poolList = new List<PoolDescription>();
			PoolDescription[] array = pools;
			foreach (PoolDescription poolDescription in array)
			{
				_poolList.Add(poolDescription);
				poolDescription.Initialize(this);
			}
		}

		private void OnDestroy()
		{
			Instance = null;
		}

		public GameObject Create(GameObject obj)
		{
			return Create(obj, Vector3.zero);
		}

		public GameObject Create(GameObject obj, Vector3 position)
		{
			foreach (PoolDescription pool in _poolList)
			{
				if (pool.Prefab.name == obj.name)
				{
					return pool.Create(obj.name, position);
				}
			}
			PoolDescription poolDescription = AddPoolElement(obj, 1);
			return poolDescription.Create(obj.name, position);
		}

		public GameObject Create(string name)
		{
			return Create(name, Vector3.zero);
		}

		public GameObject Create(string name, Vector3 position)
		{
			foreach (PoolDescription pool in _poolList)
			{
				if (pool.Prefab.name == name)
				{
					return pool.Create(name, position);
				}
			}
			UnityEngine.Debug.LogError("Prefab not found: " + name);
			return null;
		}

		public void ReturnObject(GameObject obj)
		{
			obj.SetActive(value: false);
			obj.transform.SetParent(base.transform);
		}

		public PoolDescription AddPoolElement(GameObject obj, int size)
		{
			PoolDescription poolDescription = new PoolDescription();
			poolDescription.Prefab = obj;
			poolDescription.PoolSize = size;
			poolDescription.Initialize(this);
			poolDescription.Growable = true;
			_poolList.Add(poolDescription);
			return poolDescription;
		}

		private void Update()
		{
			frame++;
		}
	}
}
